package com.atguigu.gulimall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Feign配置类
 *
 * @author xiaoping
 * @create 2020/7/3 20:49
 * @since 1.0.0
 */
@Configuration
public class GuliFeignConfig {

    /**
     * 添加拦截器，设置请求头信息
     * @return
     */
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
               //拿到请求的数据
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                //老请求
                if (attributes != null) {
                    HttpServletRequest request = attributes.getRequest();
                    //同步请求头数据，Cookie
                    String cookie = request.getHeader("Cookie");
                    //给新请求同步老请求的cookie
                    template.header("Cookie",cookie);
                }
            }
        };
    }
}
